<?php


class api1Action extends BackAction{

    private $users      = array();
    private $weibo_id   = null;    
    
    private function _ex($obj){
        if(array_key_exists('error', $obj) && array_key_exists('error_code', $obj)){
            $this->_error($obj['error']);
        }
        return $obj;
    }
    
    private function _error($error){
        echo json_encode(array('code'=>'error','data'=>$error));
        exit;
    }
    
    /**
     * 获取待分析的微博资料
     * @param type $weibo_id
     * @return type 
     */
    private function _get_users($weibo_id){
        
        if(isset ($_SESSION['api']['user'][$weibo_id])){
            return $_SESSION['api']['user'][$weibo_id];
        }
        
        $u  = ORM_Finder::findOne('DB_ANALYSIS_USER', array('weibo_id'=>$weibo_id));
        if($u){
            $u  = $u->toArray();
            $_SESSION['api']['user'][$weibo_id] = $u;
        }else{
            $u  = array();
        }
        return $u;
    }
    
    /**
     *
     * @param type $data
     * @param type $append 
     */
    private function _ok($data, $append=null){
        $re = array('code'=>'ok','data'=>$data);
        if(null != $append){
            $re = array_merge($re, $append);
        }
        echo json_encode($re);
        exit;
    }
    
    private function _get_weibo_id_json(){
        $weibo_id   = $this->params['weibo_id'];
        if(!$weibo_id){
            $this->_error('need weibo id');
        }
        return $weibo_id;
    }
    
    /**
     * 性别分析
     */
    private function _sex(){
        
        foreach ($this->users as $k1 => $v1) {
            $g  = $v1['gender'];
            $gender[$g][]  = $g;
        }
        
        foreach ($gender as $k2 => $v2) {
            DB_SEX::saveSex($this->weibo_id, $k2, count($v2));
        }
    }
    
    /**
     * 获取我的粉丝
     * @return array 
     */
    private function _my_follower_weibo_id($weibo_id=null){
        $result = array();
        $rs = ORM_Finder::find('DB_FOLLOWS', array('weibo_id' => $weibo_id), 'follow_id');
        foreach ($rs as $k1 => $v1) {
            $result[] = $v1->getFollowId();
        }
        return $result;
    }


    /**
     * 地域分析
     */
    private function _location(){
        
        if($users !=null){
            $this->users    = $users;
        }
        
        $loc    = array();
        
        foreach ($this->users as $k1 => $v1) {
            if(empty($v1['location'])){
                $loc['未知'][]  = '未知';
                continue;
            }
            $location   = explode(' ', $v1['location']);
            $loc[$location[0]][]    = $v1['location'];
        }
        
        foreach ($loc as $k3 => $v3) {
            DB_LOCATION::saveLocation($this->weibo_id, $k3, count($v3));
        }
    }
    
    /**
     * 获取用户粉丝
     */
    function actionIndex(){
        
        $gender = array();
        
        $weibo_id   = $this->_get_weibo_id_json();
        $date       = $this->params['date'];
        $token      = $this->params['token'];
            
        
        //待分析的用户
        $analysis_user  = ORM_Finder::findOne('DB_ANALYSIS_USER', array('weibo_id'=>$weibo_id));
        
        $this->weibo_id = $weibo_id;
        
        if(!$analysis_user || $date){
            
            if(!$token){
                $oauth  = ORM_Finder::findOne('DB_OAUTH');
                $token  = $oauth->getToken();
            }

            $c  = new SaeTClientV2(WB_AKEY, WB_SKEY, $token);
            
            //待分析的微博信息
            $followers  = $this->_ex($c->show_user_by_id($weibo_id));

            
            //获取粉丝列表
            $re = $this->_ex($c->followers_by_id($weibo_id, 0, 200));

            $this->set_users($re['users']);
            
            //保存关注我的人
            DB_FOLLOWS::batchSave($weibo_id, $re['users']);

            while($re['next_cursor']){
                $re = $this->_ex($c->followers_by_id($weibo_id, $re['next_cursor'], 200));
                //保存关注我的人
                DB_FOLLOWS::batchSave($weibo_id, $re['users']);

                $this->set_users($re['users']);
            }
            $followers['fetch_count']   = count($this->users);
            
            //保存分析的用户信息
            $u  = DB_ANALYSIS_USER::batch_save(array($followers)); 
            
            $_SESSION['user_arr']   = $this->users;
            $_SESSION['weibo']      = $followers;

            //分析地域
            $this->_location();
            //分析性别
            $this->_sex();
            $ids    = $this->_my_follower_weibo_id();
            $u  = $u[0]->toArray();
            $_SESSION['api']['users'][$this->weibo_id]  = $u;
            //微博用户ID
            echo json_encode(array('code'=>'ok', 'data'=>$u));
            exit;
        }
        
        //获取要分析的人的微博信息
        $u  = $this->_get_users($this->weibo_id);
        
        echo json_encode(array('code'=>'ok', 'data'=>$u));
    }
    
    /**
     * 性别分析
     */
    function actionSex(){
        $weibo_id   = $this->_get_weibo_id_json();
        
        $re     = array();
        
        $sex    = ORM_Finder::find(DB_SEX, array('weibo_id'=>$weibo_id));
        
        if(!$sex){
            $this->_error('no data');
        }
        
        foreach ($sex as $k => $v) {
            $re[$v->getGender()]    = (int)$v->getNums();
        }
        
        $this->_ok($re);
    }
    
    /**
     * 地区分析
     */
    function actionLocation(){
        
        $weibo_id   = $this->_get_weibo_id_json();
        $re     = array();
        
        $location    = ORM_Finder::find('DB_LOCATION', array('weibo_id'=>$weibo_id));
        
        if(!$location){
            $this->_error('no data');
        }
        
        $total  = ORM_Finder::findSum('DB_LOCATION', array('weibo_id'=>$weibo_id), 'nums', ' order by nums desc limit 10');
         
        foreach ($location as $k => $v) {
            $nums   = $v->getNums();
            $re[]   = array(
                'location'=>$v->getLocation(), 'nums'=>$nums, 'per'=>"".round(($nums / $total) * 100, 2)
                );
        }
        
        $this->_ok($re,array('total'=>$total));
    }
    
    function actionLocationTop(){
        $weibo_id   = $this->_get_param_json_weibo_id();
        $re     = array();
        $location    = ORM_Finder::find('DB_LOCATION', array('weibo_id'=>$weibo_id), '*', 'nums desc', 10);
        if(!$location){
            $this->_error('no data');
        }
        $re     = array();
        $total  = 0;
        foreach ($location as $k => $v) {
            $nums   = $v->getNums();
            $total  = $total + $nums;
        }
        
        foreach ($location as $k1 => $v1) {
            $nums   = $v1->getNums();
            $re[]   = array(
                'location'=>$v1->getLocation(), 'nums'=>$nums, 'per'=>"".round(($nums / $total) * 100, 2)
                );
        }
        $this->_ok($re,array('total'=>$total));
    }
    
    /**
     * 待分析的用户信息
     */
    function actionUser(){
        $weibo_id   = $this->_get_weibo_id_json();
        $rs = ORM_Finder::findOne('DB_ANALYSIS_USER', array('weibo_id'=>$weibo_id));
        if(!$rs){
            $this->_error('没有用户');
        }
        $this->_ok($rs->toArray());
    }
    
    /**
     * 自带粉丝查询
     */
    
    function actionLimit(){

        $weibo_id   = $this->_get_weibo_id_json();
        $limit      = $this->params['limit'];
        $weibo_id   = $this->_my_follower_weibo_id($weibo_id);
        $weibo_id   = implode(',', $weibo_id);
        if($limit){
            $where  = "weibo_id in($weibo_id) and followers_count>=$limit";
        }else{
            $where  = "weibo_id in($weibo_id)";
        }
        $rs         = ORM_Finder::findCount('DB_WEIBO', $where);
        $this->_ok($rs);
    }
    
    /**
     * 最后微博、评论时间
     */
    function actionLastPublish(){
        $weibo_id   = $this->_get_param_json_weibo_id();
        $ids        = $this->_my_follower_weibo_id($weibo_id);
        $ids        = implode(',', $ids);
        $where      = "weibo_id in($ids) and last_publish='0000-00-00 00:00:00'";
        $total      = ORM_Finder::findCount('DB_WEIBO', $where);
        if($total){
            $this->_error($total .' has not analysis.');
        }
        
        //今天活跃的,包含未带头像用户
        $time   = time();
        $now   = date('Y-m-d', time());
        $where1      = "weibo_id in($ids) and last_publish>='$now' ";
        
        //今日活跃，未带头像的
        $where11      = "weibo_id in($ids) and last_publish>='$now' and (profile_image_url like '%0/1' or profile_image_url like '%0/0')";
        
        $day1          = ORM_Finder::findCount('DB_WEIBO', $where1);
        //echo $day1.'<br/>';
        
        //昨天
        $pre        = date('Y-m-d', time() - 3600*24);
        $where      = "weibo_id in($ids) and last_publish<='$now' and last_publish>='$pre'";
        $day2       = ORM_Finder::findCount('DB_WEIBO', $where);
        //echo $day2.'<br/>'; 
        
        //前天
        $pre        = date('Y-m-d', time() - 3600*24 * 2);
        $now        = date('Y-m-d', time() - 3600*24 );
        $where      = "weibo_id in($ids) and last_publish<='$now' and last_publish>='$pre'";
        $day3       = ORM_Finder::findCount('DB_WEIBO', $where);
        //echo $day3.'<br/>';   
        
        $pre        = date('Y-m-d', time() - 3600*24 * 3);
        $now        = date('Y-m-d', time() - 3600*24 * 2);
        $where      = "weibo_id in($ids) and last_publish<='$now' and last_publish>='$pre'";
        $day4       = ORM_Finder::findCount('DB_WEIBO', $where);
        //echo $day4.'<br/>'; 
        
        $pre        = date('Y-m-d', time() - 3600*24 * 4);
        $now        = date('Y-m-d', time() - 3600*24 * 3);
        $where      = "weibo_id in($ids) and last_publish<='$now' and last_publish>='$pre'";
        $day5       = ORM_Finder::findCount('DB_WEIBO', $where);
        //echo $day5.'<br/>';        
        
        $pre        = date('Y-m-d', time() - 3600*24 * 5);
        $now        = date('Y-m-d', time() - 3600*24 * 4);
        $where      = "weibo_id in($ids) and last_publish<='$now' and last_publish>='$pre'";
        $day6       = ORM_Finder::findCount('DB_WEIBO', $where);
        //echo $day6.'<br/>';        
        
        $pre        = date('Y-m-d', time() - 3600*24 * 6);
        $now        = date('Y-m-d', time() - 3600*24 * 5);
        $where      = "weibo_id in($ids) and last_publish<='$now' and last_publish>='$pre'";
        $day7       = ORM_Finder::findCount('DB_WEIBO', $where);
        //echo $day7.'<br/>'; 
        
        $now        = date('Y-m-d', time() - 3600*24 * 6);
        $where      = "weibo_id in($ids) and last_publish<='$now'";
        $other      = ORM_Finder::findCount('DB_WEIBO', $where);
        //echo $other.'<br/>'; 
        $fetch_count      = $day1 + $day2+$day3 +$day4 +$day5 +$day6 +$day7 +$other;
        
        $this->_ok(array(
                    'd1'=>$day1,'d2'=>$day2,'d3'=>$day3,'d4'=>$day4,'d5'=>$day5,
                    'd6'=>$day6,'d7'=>$day7,'other'=>$other,'fetch_count'=>$fetch_count
                    ));
    }
    
    /**
     * 发微博平均数
     */
    function actionDayPublish(){
        $weibo_id       = $this->_get_param_json_weibo_id();
        $id_arr         = $this->_my_follower_weibo_id($weibo_id);
        $ids            = implode(',', $id_arr);
        $where          = "weibo_id in($ids) and day_publish='n'";
        $total          = ORM_Finder::findCount('DB_WEIBO', $where);
        if($total){
            $this->_error($total .' has not analysis.');
        }
        
        $sum_where      ="weibo_id in($ids)";
        $sum            = ORM_Finder::findSum('DB_WEIBO', $sum_where ,'day_publish');
        echo round($sum / count($id_arr), 4);
    }
    
    /**
     * 抓取微博内容，并更新用户信息
     */
    function actionBlog(){
        
        $weibo_id   = 2505074340;
        $oauth      = ORM_Finder::findOne('DB_OAUTH');
        $token      = $oauth->getToken();
        $c          = new SaeTClientV2(WB_AKEY, WB_SKEY, $token);
        $re         = $this->_ex($c->user_timeline_by_id($weibo_id));
        $result     = array();
        $json       = array();
        foreach ($re['statuses'] as $k2 => $v2) {
            $result[]   = $v2;
            if(isset($v2['retweeted_status'])){
                $result[]   = $v2['retweeted_status'];
            }            
        }

        foreach ($result as $k1 => $v1) {
            
            $blog   = ORM_Finder::findOne(DB_BLOG, array('idstr'=>$v1['idstr']));
            
            //更新用户信息
            DB_WEIBO::batch_save(array($v1['user']));
            
            if(!$blog){
                $blog   = new DB_BLOG();
                $blog->setWeiboId($weibo_id);
                $blog->setMid($v1['mid']);
                $blog->setIdstr($v1['idstr']);
                $blog->setText($v1['text']);
                $blog->setSource($v1['source']);
                $blog->setFavorited((int)$v1['favorited']);
                $blog->setTruncated((int)$v1['truncated']);
                $blog->setGeo((int)$v1['geo']);
                $blog->setRepostsCount($v1['reposts_count']);
                $blog->setCommentsCount($v1['comments_count']);
                $blog->setUsers(serialize($v1['user']));
                $blog->setCreatedAt(date('Y-m-d H:i:s', strtotime($v1['created_at'])));
                
                if(isset($v1['thumbnail_pic'])){
                    $blog->setThumbnailPic($v1['thumbnail_pic']);
                }
                
                if(isset($v1['bmiddle_pic'])){
                    $blog->setBmiddlePic($v1['bmiddle_pic']);
                }
                
                if(isset($v1['original_pic'])){
                    $blog->setOriginalPic($v1['original_pic']);
                }

                //是转发的
                if(isset($v1['retweeted_status'])){
                    $blog->setRetweetedStatus($v1['retweeted_status']['idstr']);
                }
                
                $blog->save();
            }else{
                $blog->setRepostsCount($v1['reposts_count']);
                $blog->setCommentsCount($v1['comments_count']);
                $blog->save();
            }
            
            $json[] = $blog->toArray();

        }
        
        echo $this->_ok($json);
    }
    
    /**
     * 抓取评论
     */
    function actionComments(){
        set_time_limit(0);
        //$weibo_id   = $this->_get_weibo_id_json();
        $blog_id    = $this->params['blog_id'];
        $weibo_id   = '2505074340';
        $oauth      = ORM_Finder::findOne('DB_OAUTH');
        $token      = $oauth->getToken();
        $c          = new SaeTClientV2(WB_AKEY, WB_SKEY, $token);
        $comments   = ORM_Finder::find('DB_BLOG', "comment_up='0000-00-00 00:00:00' and comments_count>0", 'id,idstr', 'id asc', 100);
        $store      = array();
        
        if($comments){
            foreach ($comments as $k1 => $v1) {
                $re         = $this->_ex($c->get_comments_by_sid($v1->getIdstr(), 1, 200));
                //更新或保存评论
                $save   = DB_COMMENT::store($re['comments']);
                $store  = array_merge($store, $save);
                $v1->setCommentUp(date('Y-m-d H:i:s'));
                $v1->save();
            }
            $this->_ok($store);
        }
        $this->_error('no data to update.');
        
    }
    
    /**
     * 微博多少人看到，传播力
     */
    function actionCover(){
        $weibo_id   = 2505074340;
        $comment_id = null;
        $user       = ORM_Finder::findOne(DB_ANALYSIS_USER, array('weibo_id'=>$weibo_id));
        if(!$user){
            $this->_error('no this user');
        }
        
        //自己的粉丝数影响力
        $follower_count = $user->getFollowersCount();
        $fetch_count    = $user->getFetchCount();
        if($follower_count>5000){
            $all    = round(($fetch_count / 5000 ) * $follower_count);
        }else{
            $all    = $fetch_count;
        }
        
        if($comment_id){
            $where  = "weibo_id = $weibo_id and mid=$comment_id";
        }else{
            $where  = "weibo_id = $weibo_id";
        }
        
        /**
         * 没有评论
         */
        $comments   = ORM_Finder::find('DB_COMMENT', $where, 'from_id');
        if(!$comments){
            $this->_ok($all);
        }
        
        /**
         * 总的影响力
         */
        
        $from_id    = array();
        foreach ($comments as $k1 => $v1) {
            $u  = unserialize($v1->getUser());
            //$all    = $all + $u['followers_count'];
            $from_id[]  = $v1->getFromId();
            $step ++;
        }
        $from_id    = array_unique($from_id);
        $from_id    = implode(',', $from_id);
        $num        = ORM_Finder::findSum('DB_WEIBO', "weibo_id in($from_id)", 'followers_count');
        $total      = $all+$num;
        //每篇微博影响力
        $count  = ORM_Finder::findCount('DB_BLOG', array('weibo_id'=>$weibo_id));
        
        //average 看到评论的人除以总的微博数
        $this->_ok($total, array('average'=>round($total / $count)));
    }
    
    /**
     * 用户未上传头像数
     */
    function actionAvatar(){
        
        $weibo_id   = $this->_get_weibo_id_json();
        
        $user       = ORM_Finder::findOne('DB_ANALYSIS_USER', array('weibo_id'=>$weibo_id));
        if(!$user){
            $this->_error('no this user');
        }
        
        $ids        = $this->_my_follower_weibo_id($weibo_id);
        $ids        = implode(',', $ids);
        
        $where      = "weibo_id in($ids) and (profile_image_url like '%0/1' or profile_image_url like '%0/0')";
        
        $total      = ORM_Finder::findCount('DB_WEIBO', $where);
        
        $fetch_count    = $user->getFetchCount();
        
        $user->setFetchAvatar($fetch_count-$total);
        $user->save();   
        $this->_ok($total, array('fetch_count'=>$fetch_count,'active'=>$fetch_count-$total));

    }
    /**
     * 分析程序
     */
    function actionRun(){
        $this->setPageTitle('简单分析');
        $weibo_id_arr   = $this->_my_follower_weibo_id();
        $rs             = DB_WEIBO::getMyFollower($weibo_id_arr);
        $list           = array();
        
        foreach ($rs as $k => $v){
            $created_at = explode('-', $v->getCreatedAt());
            $list[$created_at[0]][]  = $v;
        }
        
        $this->set('list', $list);
        $this->render(null, 'api');
    }
    
    protected function set_users($users){
        foreach ($users as $k => $v) {
            $this->users[]  = $v;
        }        
    }
    
    function actionTest(){
        $login  = new WeiboLogin('weibo19882@126.com', 'dehua2011','3_5bc5bf3d3fa09492e806daaee0f9754092ae315a','ca40', '2388412533');
        $re     = $login->showTag('1740292044');
        print_r($re);
    }
}
?>
